<template>
	<div class="playground" @contextmenu.prevent>
		<FirstLevel v-if="difficultyLevel === 'first'" @complete="handleComplete" />
		<SecondLevel v-if="difficultyLevel === 'second'" @complete="handleComplete" />
		<ThridLevel v-if="difficultyLevel === 'third'" @complete="handleComplete" />
		<div v-if="difficultyLevel !== 'first' && difficultyLevel !== 'second' && difficultyLevel !== 'third'">
			未知关卡: {{ difficultyLevel }}
		</div>
	</div>
</template>

<script setup>
	import FirstLevel from '@/views/game/pk/single/level/FirstLevel.vue'
	import SecondLevel from '@/views/game/pk/single/level/SecondLevel.vue'
	import ThridLevel from '@/views/game/pk/single/level/ThridLevel.vue'
	import { useRoute, useRouter } from 'vue-router'
	import { defineEmits, defineProps, onUnmounted, computed } from 'vue'
	import { GameObject } from '@/assets/scripts/GameObject'

	// 定义props，接收level参数
	const props = defineProps({
		level: {
			type: String,
			default: 'first'
		}
	})

	const emit = defineEmits(['complete'])
	const route = useRoute()
	const router = useRouter()
	
	// 如果传入了props.level，则使用props.level，否则从路由参数中获取
	const difficultyLevel = computed(() => {
		console.log('Props level:', props.level)
		console.log('Route params:', route.params)
		const level = props.level || route.params.level || 'first'
		console.log('Final difficultyLevel:', level)
		return level
	})

	// 处理关卡完成事件
	const handleComplete = () => {
		try {
			// 清理所有游戏对象，防止内存泄漏
			if (typeof GameObject.clearAll === 'function') {
				GameObject.clearAll()
			}
			
			// 触发上层组件的完成事件
			emit('complete')
		} catch (error) {
			console.error('处理关卡完成事件时出错:', error)
			// 尝试回到关卡选择页面
			router.go(-1)
		}
	}
	
	// 清理游戏资源
	onUnmounted(() => {
		try {
			if (typeof GameObject.clearAll === 'function') {
				GameObject.clearAll()
			}
		} catch (error) {
			console.warn('清理游戏对象时出错:', error)
		}
	})
</script>

<style scoped>
	.playground {
		width: 100%;
		height: 100%;
		margin: 0;
		padding: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		overflow: hidden;
	}
</style>